import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import LoginRegister from '../views/LoginRegister.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: LoginRegister
    },
    {
      path: '/admin',
      name: 'AdminLayout',
      component: () => import('@/views/admin/AdminLayout.vue'),
      meta: { requiresAuth: true, requiresAdmin: true },
      children: [
        {
          path: '',
          redirect: '/admin/elderly'
        },
        {
          path: 'elderly',
          name: 'AdminElderly',
          component: () => import('@/views/admin/ElderlyManagement.vue')
        },
        {
          path: 'elderly/:id',
          name: 'AdminElderlyDetail',
          component: () => import('@/views/admin/ElderlyDetail.vue')
        },
        {
          path: 'reports',
          name: 'AdminReports',
          component: () => import('@/views/admin/Reports.vue')
        }
      ]
    },
    {
      path: '/user',
      name: 'UserLayout',
      component: () => import('@/views/user/UserLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          redirect: '/user/profile'
        },
        {
          path: 'profile',
          name: 'UserProfile',
          component: () => import('@/views/user/ElderlyProfile.vue')
        },
        {
          path: 'health',
          name: 'UserHealth',
          component: () => import('@/views/user/HealthData.vue')
        },
        {
          path: 'medication',
          name: 'UserMedication',
          component: () => import('@/views/user/MedicationRecords.vue')
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 初始化用户状态
  if (!userStore.currentUser) {
    userStore.initFromStorage()
  }
  
  // 如果访问根路径，根据用户角色重定向
  if (to.path === '/') {
    const user = userStore.currentUser
    if (user && user.role === 'admin') {
      next('/admin')
    } else {
      next('/user')
    }
    return
  }
  
  // 确保用户已登录
  if (to.meta.requiresAuth && !userStore.currentUser) {
    userStore.setDefaultUser()
    const user = userStore.currentUser
    if (user && (user as any).role === 'admin') {
      next('/admin')
    } else {
      next('/user')
    }
    return
  }
  
  // 检查管理员权限
  if (to.meta.requiresAdmin && userStore.currentUser?.role !== 'admin') {
    next('/user')
    return
  }
  
  // 管理员访问用户页面时重定向
  if (to.path === '/user' && userStore.currentUser?.role === 'admin') {
    next('/admin')
    return
  }
  
  next()
})

export default router
